# -*- coding: utf-8 -*- 
# @Time : 2020-12-16 23:21 
# @Author : derek.zhang 
# @File : user_group.py 
# @Software: PyCharm
from django.contrib.auth.models import Group

from appinput.models import App
from rightadmin.models import Permission


def is_admin_group(user):
    '''
    判断是否为前台管理员组
    :param user:
    :return:
    '''
    try:
        user_group = Group.objects.get(user=user)
    except Exception as e:
        return False
    # 前台管理员组
    if "admin" == user_group:
        return False
    else:
        return True


def is_app_admin(app_id, user):
    '''
    判断是否为APP 管理人员
    :param app_id:
    :param user:
    :return:
    '''
    app = App.objects.get(id=app_id)
    if user == app.manage_user or is_admin_group(user):
        return True
    return False

def get_app_admin(app_id):
    '''
    获取APP 管理员
    :param app_id:
    :return:
    '''
    return App.objects.get(id = app_id).manage_user


def get_app_user(app_id, action_id, env_id):
    '''
    获取app 各个权限的相关人员
    :param app_id:
    :param action_id:
    :param env_id:
    :return:
    '''
    filter_dict = dict()
    filter_dict['app_name__id'] = app_id
    filter_dict['action_name__id'] = action_id
    if env_id != '0':
        filter_dict['env_name__id'] = env_id
    permission_set = Permission.objects.get(**filter_dict)
    user_set = permission_set.main_user.all()
    return user_set

def is_right(app_id, action_id, env_id, user):
    '''
    判断是否具有app 相关环境的相关权限
    :param app_id:
    :param action_id:
    :param env_id:
    :param user:
    :return:
    '''
    if is_app_admin(app_id, user):
        return True
    filter_dict = dict()
    filter_dict['app_name__id'] = app_id
    filter_dict['action_name__id'] = action_id
    if env_id != '0':
        filter_dict['env_name__id'] = env_id
    try:
        permission_set = Permission.objects.get(**filter_dict)
        user_set = permission_set.main_user
        if user in user_set:
            return True
    except Permission.DoesNotExist:
        pass
    return False
